<?php

namespace App\Services\Infra;

use App\Exceptions\ChargeRecordException;
use App\Models\ChargeRecord;
use App\Models\Device;
use App\Models\InstallInfo;
use DB;

class ChargeRecordManager {

    /**
     * 根据 id 获取充值记录
     * @param  integer  $orderId 
     * @return           
     */
    public function getChageRecordById($orderId){
        $chargeRecord = ChargeRecord::where('id', $orderId)->first();
        return $chargeRecord;
    }

    /**
     * 根据订单号查充值记录
     * @param  string  $orderNumber 
     * @return               
     */
    public function findByOrderNumber($orderNumber){
        $chargeRecord = ChargeRecord::where('order_number', $orderNumber)->first();
        if(is_null($chargeRecord)){
            throw new ChargeRecordException('notFound');
        }
        return $chargeRecord;
    }

    /**
     * 根据传入数据生成订单
     * @param  array $params 
     * @return          
     */
    public function createOrder($params){
        $chargeRecord = ChargeRecord::create($params);
        if(is_null($chargeRecord)){
            throw new ChargeRecordException('chargeRecord.add');
        }
        return $chargeRecord;
    }

    /**
     * 获取充值记录
     * @param  string  $condition 
     * @return              
     */
    public function findChargeListByQuery($condition)
    {
        $ids = DB::select('select max(a.id) as id from (select * from charge_records where status>0) as a group by a.device_id');
        $query = ChargeRecord::latest();
        if(!empty($condition)){
            $deviceIds1 = Device::where('code', 'like', '%'.$condition.'%')->get()->pluck('id');
            $deviceCodes = InstallInfo::where('customer_name', 'like', '%'.$condition.'%')->select('device_code')->get();
            $deviceIds2 = Device::whereIn('code', $deviceCodes->pluck('device_code'))->select('id')->get();
            $query->whereIn('device_id', array_merge($deviceIds1->toArray(), $deviceIds2->pluck('id')->toArray()));
        }
        $query->whereIn('id', $ids);
        return $query;
    }

    /**
     * 根据查询条件查询充值记录
     * @param  string  $column 
     * @param  string $cndition     
     * @return          
     */
    public function getChargeListByQueryColumn($column, $cndition)
    {
        return ChargeRecord::where($column, $cndition);
    }

    public function getChargeBuilderOrderByCreatedAt()
    {
        return ChargeRecord::latest();
    }
    
    
}